package com.blackshadowgame.rps.slice;

import com.blackshadowgame.rps.*;
import com.blackshadowgame.rps.client.GameClient;
import com.blackshadowgame.utils.DeviceUtils;
import com.blackshadowgame.utils.LogUtil;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.distributedschedule.interwork.DeviceInfo;
import ohos.utils.IntervalTimer;

import java.util.List;

public class HomeSlice extends BaseSlice implements Component.ClickedListener {
    private static final String TAG = HomeSlice.class.getSimpleName();
    public String getTag(){
        return TAG;
    }
    protected int getTextLogId(){
        return ResourceTable.Id_text_info;
    }

//    private IGameServiceInterface gameService = null;

//    private Queue<String> infoQueue = new ArrayDeque<>();
//    private Text txtInfo = null;

    private Button buttonHost = null;
    private Button buttonJoinRemote = null;
    private Button buttonPlay = null;

    private DeviceInfo targetDevice = null;
    private String localDeviceName = null;
    private Text txtResult = null;
    private Text txtService = null;

    public int getLayoutId(){
        return ResourceTable.Layout_ability_main;
    }

    private IntervalTimer gameTimer = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        localDeviceName = ohos.system.DeviceInfo.getName();
        queryDevices();

        startGameLoop();
    }

    protected void initUIComponent(){
        super.initUIComponent();
        buttonHost = (Button)findComponentById(ResourceTable.Id_buttonHost);
        if(buttonHost != null){
//            buttonHost.setText("开始新游戏");
            buttonHost.setClickedListener(this);
        }

        buttonJoinRemote = (Button)findComponentById(ResourceTable.Id_buttonJoinRemote);
        if(buttonJoinRemote != null){
            buttonJoinRemote.setText("搜索游戏");
            buttonJoinRemote.setClickedListener(this);
        }

        buttonPlay = (Button)findComponentById(ResourceTable.Id_buttonPlay);
//        buttonPlay.setText("进入游戏");
        buttonPlay.setClickedListener(this);

        txtResult = (Text)findComponentById(ResourceTable.Id_text_result);
        txtService = (Text)findComponentById(ResourceTable.Id_text_service);

        addInfo("加载界面...完成");
        txtService.setText("游戏服务:" + GameClient.getInstance().getServiceName());
//        addInfo("本机名称：" + localDeviceName);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    public List<DeviceInfo> queryDevices(){
        addInfo("开始查询在线设备...");
        List<DeviceInfo> devices = DeviceUtils.getAllDevices();
        if(devices.size()<=0){
            addInfo("在线设备: 0");
            buttonJoinRemote.setText("搜索游戏");
        }else{
            int n = 1;
            DeviceInfo firstDevice = null;
            for(DeviceInfo device: devices){
                addInfo(String.format("[%d] 设备名：%s，类型: %s", n, device.getDeviceName(), device.getDeviceType().toString()));
                if(firstDevice == null && device.getDeviceType() == DeviceInfo.DeviceType.SMART_PHONE){
                    firstDevice = device;
                }
            }

//            DeviceInfo firstDevice = devices.get(0);
            if(firstDevice!=null){
                targetDevice = firstDevice;
                buttonJoinRemote.setText(String.format("连接远程游戏: %s", firstDevice.getDeviceName()));
            }
        }

        return devices;
    }

    @Override
    public void onClick(Component component) {
        if(component == buttonHost){
            onHostGame();
        }else if(component == buttonJoinRemote){
            onJoinGame();
        }else if(component == buttonPlay){
            onPlayGame();
        }
    }

    private void onHostGame(){
        addInfo("连接本地游戏服务");
        txtResult.setText("当前游戏服务：本地");

        GameClient.getInstance().disconnect();
        GameClient.getInstance().connectLocalGameService();
    }

    private void onJoinGame(){
        if(targetDevice==null){
            queryDevices();
        }else{
            // connect to
            addInfo(String.format("准备开始游戏...对手：%s", targetDevice.getDeviceName()));

            GameClient.getInstance().disconnect();
            GameClient.getInstance().connectGameService(targetDevice);

            txtResult.setText("当前游戏服务：" + targetDevice.getDeviceName());
        }
    }

    private void onPlayGame(){
        if(!GameClient.getInstance().testConnection()){
            addInfo("没有游戏连接，无法开始游戏");
            return;
        }

        addInfo("准备进入游戏...");

        int pid = GameClient.getInstance().joinGame("");
        if(pid < 0){
            txtResult.setText("加入游戏失败!");
            return;
        }

        goWaitSlice();
    }

    private void startGameLoop(){
        if(gameTimer == null){
            gameTimer = new IntervalTimer(1000, 1000) {
                @Override
                public void onInterval(long l) {
                    runInMainThread(new Runnable() {
                        @Override
                        public void run() {
                            onLoop(l);
                        }
                    });
                }

                @Override
                public void onFinish() {
                    gameTimer.schedule();
                }
            };
            gameTimer.schedule();
        }
    }

    protected void onLoop(long deltaTime){
        if(GameClient.getInstance().isConnected()){
            txtService.setText("游戏服务:" + GameClient.getInstance().getServiceName() + ", ID: " + GameClient.getInstance().getPlayerId());

            GameResultData result = GameClient.getInstance().queryGameResult();

            String info = result.getInfo();
            txtResult.setText(info);

            if(result.state == GameCode.GAME_STATE_NEW){
                addInfo("新游戏开始...");
            }else if(result.state == GameCode.GAME_STATE_WAITING_FOR_PLAYER){
                addInfo("等待玩家进入游戏...");
            }else if(result.state == GameCode.GAME_STATE_WAITING_FOR_INPUT){
                addInfo("玩家已经到齐，准备开始游戏...");
            }else if(result.state == GameCode.GAME_STATE_FINISHED){
                addInfo("游戏结束");
            }else{
                // 其他未知状态
            }
            addInfo(info);
        }else {
            txtResult.setText("请先连接游戏服务...");
        }
    }
}
